<template>
  <div class="spouse-selector">
    <el-button type="primary" size="small" @click="showSelector" class="select-btn">
      <i class="el-icon-plus"></i> 选择配偶
    </el-button>

    <!-- 配偶选择对话框 -->
    <el-dialog
      title="选择配偶"
      :visible.sync="dialogVisible"
      width="90%"
      @close="handleDialogClose"
      class="spouse-dialog"
      :close-on-click-modal="false"
      top="5vh"
    >
      <!-- 搜索区 -->
      <el-form :inline="true" class="search-bar" @submit.native.prevent style="margin-right: 5px">
        <el-form-item label="姓名">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入配偶姓名"
            size="small"
            clearable
            @keyup.enter.native="handleSearch"
            class="search-input"
          />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="searchGender" placeholder="全部" size="small" clearable class="gender-select">
            <el-option label="全部" value=""></el-option>
            <el-option label="男" value="M"></el-option>
            <el-option label="女" value="F"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="handleSearch" class="search-btn">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button size="small" @click="handleReset" class="reset-btn">重置</el-button>
        </el-form-item>
        <el-form-item style="float:right; margin-left:auto;">
          <el-button type="success" @click="showAddSpouse" class="add-spouse-btn">
            <i class="el-icon-plus"></i> 新增配偶
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 已选择的配偶列表 -->
      <div v-if="selectedSpouses.length > 0" class="selected-spouses-section">
        <h4>已选择的配偶（可拖拽调整顺序）：</h4>
        <div class="selected-spouses-list">
          <div
            v-for="(spouse, index) in selectedSpouses"
            :key="spouse.id"
            class="selected-spouse-item"
            draggable="true"
            @dragstart="handleDragStart(index)"
            @dragover.prevent
            @drop="handleDrop(index)"
          >
            <div class="spouse-order">{{ getSpouseOrderText(index) }}</div>
            <div class="spouse-info">
              <span class="spouse-name">{{ spouse.name }}</span>
              <span class="spouse-gender">{{ spouse.gender === 'M' ? '男' : '女' }}</span>
            </div>
            <div class="spouse-actions">
              <el-button size="mini" type="danger" @click="removeSelectedSpouse(spouse)">移除</el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 配偶列表表格 -->
      <div class="table-container">
        <el-table
          ref="spouseTable"
          :data="spouseList"
          v-loading="loading"
          border
          stripe
          class="spouse-table"
          @selection-change="handleSelectionChange"
          @row-click="handleRowClick"
          highlight-current-row
          height="400"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="name" label="姓名" width="120"></el-table-column>
          <el-table-column prop="gender" label="性别" width="80">
            <template slot-scope="scope">
              <el-tag :type="scope.row.gender === 'M' ? 'primary' : 'danger'" class="gender-tag">
                {{ scope.row.gender === 'M' ? '男' : '女' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="birthDate" label="出生日期" width="120"></el-table-column>
          <el-table-column prop="nativePlace" label="籍贯" width="120"></el-table-column>
          <el-table-column prop="currentAddress" label="现居地址" min-width="200"></el-table-column>
          <el-table-column prop="status" label="状态" width="80">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status === '在世' ? 'success' : 'info'" class="status-tag">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="contact" label="联系方式" width="120"></el-table-column>
        </el-table>
      </div>

      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.current"
          :page-sizes="[10, 20, 50]"
          :page-size="pagination.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          class="spouse-pagination"
        />
      </div>

      <!-- 底部按钮区 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" class="cancel-btn">取消</el-button>
        <el-button type="primary" @click="handleConfirm" :disabled="selectedSpouses.length === 0" class="confirm-btn">
          确认选择 ({{ selectedSpouses.length }})
        </el-button>
      </div>
    </el-dialog>

    <!-- 新增配偶对话框 -->
    <el-dialog
      title="新增配偶"
      :visible.sync="addDialogVisible"
      width="60%"
      @close="handleAddDialogClose"
      class="add-spouse-dialog"
      :close-on-click-modal="false"
    >
      <el-form
        :model="spouseForm"
        :rules="spouseRules"
        ref="spouseForm"
        label-width="100px"
        class="spouse-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="spouseForm.name" placeholder="请输入配偶姓名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="spouseForm.gender">
                <el-radio label="M">男</el-radio>
                <el-radio label="F">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birthDate">
              <el-date-picker
                v-model="spouseForm.birthDate"
                type="date"
                placeholder="选择出生日期"
                style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="籍贯" prop="nativePlace">
              <el-input v-model="spouseForm.nativePlace" placeholder="请输入籍贯"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="现居地址" prop="currentAddress">
          <el-input v-model="spouseForm.currentAddress" placeholder="请输入现居地址"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="spouseForm.contact" placeholder="请输入联系方式"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="spouseForm.status">
            <el-radio label="在世">在世</el-radio>
            <el-radio label="已故">已故</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false" class="cancel-btn">取 消</el-button>
        <el-button type="primary" @click="handleAddSubmit" :loading="submitLoading" class="submit-btn">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  searchSpouseByName,
  getSpouseByGender,
  createSpouse,
  getSpouseList
} from '@/api/spouse'

export default {
  name: 'SpouseSelector',
  props: {
    // 已选择的配偶ID列表
    selectedSpouseIds: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      dialogVisible: false,
      addDialogVisible: false,
      loading: false,
      submitLoading: false,
      spouseList: [],
      selectedSpouses: [],
      searchKeyword: '',
      searchGender: '',
      draggedIndex: null, // 拖拽索引
      spouseForm: {
        name: '',
        gender: 'F',
        birthDate: '',
        nativePlace: '',
        currentAddress: '',
        contact: '',
        status: '在世'
      },
      spouseRules: {
        name: [
          { required: true, message: '请输入配偶姓名', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ]
      },
      pagination: {
        current: 1,
        size: 10,
        total: 0
      }
    }
  },
  methods: {
    // 显示选择器
    showSelector() {
      this.dialogVisible = true
      this.loadSpouseList()
    },

    // 加载配偶列表
    async loadSpouseList() {
      this.loading = true
      try {
        let response
        if (this.searchKeyword) {
          response = await searchSpouseByName(this.searchKeyword)
        } else if (this.searchGender) {
          response = await getSpouseByGender(this.searchGender)
        } else {
          // 默认加载所有配偶信息（分页）
          response = await getSpouseList({ page: 1, size: 10 })
        }
        this.spouseList = response || []
        this.pagination.total = this.spouseList.length

        // 设置已选择的配偶
        this.$nextTick(() => {
          this.setSelectedSpouses()
        })
      } catch (error) {
        this.$message.error('加载配偶信息失败')
        console.error(error)
      } finally {
        this.loading = false
      }
    },

    // 设置已选择的配偶
    setSelectedSpouses() {
      // 根据selectedSpouseIds设置已选择的配偶
      this.selectedSpouses = this.spouseList.filter(spouse =>
        this.selectedSpouseIds.includes(spouse.id)
      )
      
      // 设置表格的选中状态
      this.$nextTick(() => {
        this.selectedSpouses.forEach(spouse => {
          const row = this.spouseList.find(item => item.id === spouse.id)
          if (row) {
            this.$refs.spouseTable.toggleRowSelection(row, true)
          }
        })
      })
    },

    // 搜索
    handleSearch() {
      this.pagination.current = 1
      this.loadSpouseList()
    },

    // 重置搜索
    handleReset() {
      this.searchKeyword = ''
      this.searchGender = ''
      this.handleSearch()
    },

    // 显示新增配偶对话框
    showAddSpouse() {
      // 跳转到配偶管理模块
      this.$router.push('/spouse')
      // 关闭当前对话框
      this.dialogVisible = false
    },

    // 新增配偶提交
    async handleAddSubmit() {
      try {
        await this.$refs.spouseForm.validate()
        this.submitLoading = true

        await createSpouse(this.spouseForm)
        this.$message.success('新增配偶成功')
        this.addDialogVisible = false
        this.loadSpouseList()
      } catch (error) {
        this.$message.error('新增配偶失败')
        console.error(error)
      } finally {
        this.submitLoading = false
      }
    },

    // 选择变化
    handleSelectionChange(selection) {
      // 合并新选择的配偶，避免覆盖
      const newSpouses = selection.filter(spouse => 
        !this.selectedSpouses.some(selected => selected.id === spouse.id)
      )
      this.selectedSpouses = [...this.selectedSpouses, ...newSpouses]
    },

    // 行点击事件
    handleRowClick(row, column, event) {
      // 如果点击的是复选框列，不处理（避免重复触发）
      if (column.type === 'selection') {
        return
      }
      
      // 切换行的选中状态
      this.$refs.spouseTable.toggleRowSelection(row)
    },

    // 确认选择
    handleConfirm() {
      const selectedSpouses = this.selectedSpouses
      this.$emit('confirm', selectedSpouses)
      this.dialogVisible = false
    },

    // 对话框关闭
    handleDialogClose() {
      this.searchKeyword = ''
      this.searchGender = ''
      this.selectedSpouses = []
    },

    // 新增对话框关闭
    handleAddDialogClose() {
      this.$refs.spouseForm && this.$refs.spouseForm.resetFields()
    },

    // 分页大小变化
    handleSizeChange(size) {
      this.pagination.size = size
      this.loadSpouseList()
    },

    // 当前页变化
    handleCurrentChange(current) {
      this.pagination.current = current
      this.loadSpouseList()
    },

    // 拖拽开始
    handleDragStart(index) {
      this.draggedIndex = index;
    },

    // 拖拽结束
    handleDrop(index) {
      if (this.draggedIndex !== null && this.draggedIndex !== index) {
        const [movedItem] = this.selectedSpouses.splice(this.draggedIndex, 1);
        this.selectedSpouses.splice(index, 0, movedItem);
        this.draggedIndex = null;
      }
    },

    // 移除已选择的配偶
    removeSelectedSpouse(spouse) {
      const index = this.selectedSpouses.findIndex(s => s.id === spouse.id);
      if (index !== -1) {
        this.selectedSpouses.splice(index, 1);
      }
    },

    // 获取配偶排序文本
    getSpouseOrderText(index) {
      // 根据配偶性别显示不同称谓
      const spouse = this.selectedSpouses[index]
      const isMaleSpouse = spouse && spouse.gender === 'M'
      
      if (index === 0) {
        return isMaleSpouse ? '正夫' : '正室';
      } else if (index === 1) {
        return isMaleSpouse ? '侧夫' : '侧室';
      } else if (index === 2) {
        return isMaleSpouse ? '三夫' : '三房';
      } else if (index === 3) {
        return isMaleSpouse ? '四夫' : '四房';
      } else if (index === 4) {
        return isMaleSpouse ? '五夫' : '五房';
      } else if (index === 5) {
        return isMaleSpouse ? '六夫' : '六房';
      } else if (index === 6) {
        return isMaleSpouse ? '七夫' : '七房';
      } else if (index === 7) {
        return isMaleSpouse ? '八夫' : '八房';
      } else if (index === 8) {
        return isMaleSpouse ? '九夫' : '九房';
      } else if (index === 9) {
        return isMaleSpouse ? '十夫' : '十房';
      } else {
        return isMaleSpouse ? `${index + 1}夫` : `${index + 1}房`; // 默认显示序号
      }
    }
  }
}
</script>

<style scoped>
/* 选择按钮样式 */
.select-btn {
  background: linear-gradient(90deg, #6a82fb 0%, #fc5c7d 100%);
  border: none;
  color: #fff;
  font-weight: bold;
  border-radius: 8px;
  transition: all 0.3s;
}

.select-btn:hover {
  background: linear-gradient(90deg, #fc5c7d 0%, #6a82fb 100%);
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(106, 130, 251, 0.3);
}

/* 对话框样式 */
.spouse-dialog ::v-deep .el-dialog {
  border-radius: 16px;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.18);
  background: #fafdff;
  margin: 0 auto !important;
}

.spouse-dialog ::v-deep .el-dialog__body {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

.spouse-dialog ::v-deep .el-dialog__header {
  padding: 20px 20px 0 20px;
  border-bottom: 1px solid #e4e7ed;
}

.add-spouse-dialog ::v-deep .el-dialog {
  border-radius: 16px;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.18);
  background: #fafdff;
}

/* 搜索区样式 */
.search-bar {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 12px;
  padding: 16px 0;
}

.search-bar ::v-deep .el-form-item {
  margin-bottom: 0;
  margin-right: 16px;
}

.search-bar ::v-deep .el-form-item__label {
  font-weight: 500;
  color: #606266;
  padding-right: 8px;
}

.search-input {
  width: 200px;
}

.gender-select {
  width: 120px;
}

.search-btn {
  background: #409EFF;
  border-color: #409EFF;
  color: #fff;
  font-weight: 500;
  transition: all 0.3s;
  height: 32px;
  padding: 0 16px;
}

.search-btn:hover {
  background: #66b1ff;
  border-color: #66b1ff;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.reset-btn {
  background: #fff;
  border: 1px solid #dcdfe6;
  color: #606266;
  transition: all 0.3s;
  height: 32px;
  padding: 0 16px;
}

.reset-btn:hover {
  background: #f5f7fa;
  border-color: #409EFF;
  color: #409EFF;
}

.add-spouse-btn {
  background: linear-gradient(90deg, #67c23a 0%, #85ce61 100%);
  border: none;
  color: #fff;
  font-weight: bold;
  transition: all 0.3s;
  height: 32px;
  padding: 0 16px;
}

.add-spouse-btn:hover {
  background: linear-gradient(90deg, #85ce61 0%, #67c23a 100%);
  transform: translateY(-1px);
}

/* 已选择的配偶列表样式 */
.selected-spouses-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f0f9eb;
  border-radius: 8px;
  border: 1px solid #e1f3d8;
}

.selected-spouses-section h4 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #67c23a;
  font-size: 16px;
  font-weight: bold;
}

.selected-spouses-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.selected-spouse-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background-color: #fff;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  cursor: grab;
  transition: all 0.2s ease;
}

.selected-spouse-item:hover {
  background-color: #f5f7fa;
  border-color: #dcdfe6;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.spouse-order {
  width: 24px;
  height: 24px;
  line-height: 24px;
  text-align: center;
  background-color: #409EFF;
  color: #fff;
  border-radius: 50%;
  margin-right: 10px;
  font-size: 14px;
  font-weight: bold;
  flex-shrink: 0;
}

.spouse-info {
  flex-grow: 1;
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 14px;
  color: #303133;
}

.spouse-name {
  font-weight: 500;
}

.spouse-gender {
  font-size: 12px;
  color: #909399;
}

.spouse-actions {
  flex-shrink: 0;
}

/* 表格容器样式 */
.table-container {
  margin-bottom: 20px;
}

/* 表格样式 */
.spouse-table {
  font-size: 14px;
  border-radius: 10px;
  overflow: hidden;
  width: 100% !important;
}

.spouse-table ::v-deep .el-table__header th {
  background: #f5f7fa;
  color: #606266;
  font-weight: 600;
  border-bottom: 2px solid #e4e7ed;
}

.spouse-table ::v-deep .el-table__row {
  cursor: pointer;
  transition: all 0.3s;
}

.spouse-table ::v-deep .el-table__row:hover {
  background-color: #f0f9ff !important;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.spouse-table ::v-deep .el-table__body td {
  border-bottom: 1px solid #ebeef5;
  padding: 12px 0;
}

.gender-tag {
  border-radius: 6px;
  font-size: 12px;
  padding: 4px 8px;
}

.status-tag {
  border-radius: 6px;
  font-size: 12px;
  padding: 4px 8px;
}

/* 分页器容器样式 */
.pagination-container {
  margin-top: 20px;
  text-align: right;
  padding: 16px 0;
}

/* 分页器样式 */
.spouse-pagination {
  margin: 0;
}

.spouse-pagination ::v-deep .el-pager li {
  border-radius: 6px;
  transition: background 0.2s;
}

.spouse-pagination ::v-deep .el-pager li.active {
  background: #6a82fb;
  color: #fff;
}

/* 对话框底部按钮 */
.dialog-footer {
  padding: 16px 0 0 0;
  text-align: right;
  border-top: 1px solid #e4e7ed;
  margin-top: 20px;
}

.dialog-footer .el-button {
  min-width: 80px;
  border-radius: 8px;
  font-weight: 500;
  margin-left: 12px;
  transition: all 0.3s;
}

.confirm-btn {
  background: linear-gradient(90deg, #6a82fb 0%, #fc5c7d 100%);
  border: none;
  color: #fff;
  font-weight: bold;
}

.confirm-btn:hover {
  background: linear-gradient(90deg, #fc5c7d 0%, #6a82fb 100%);
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(106, 130, 251, 0.3);
}

.cancel-btn {
  background: #fff;
  border: 1px solid #dcdfe6;
  color: #606266;
}

.cancel-btn:hover {
  background: #f5f7fa;
  border-color: #6a82fb;
  color: #6a82fb;
}

.submit-btn {
  background: linear-gradient(90deg, #6a82fb 0%, #fc5c7d 100%);
  border: none;
  color: #fff;
  font-weight: bold;
}

.submit-btn:hover {
  background: linear-gradient(90deg, #fc5c7d 0%, #6a82fb 100%);
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(106, 130, 251, 0.3);
}

/* 表单样式 */
.spouse-form ::v-deep .el-form-item {
  margin-bottom: 20px;
}

.spouse-form ::v-deep .el-input,
.spouse-form ::v-deep .el-select,
.spouse-form ::v-deep .el-date-picker {
  width: 100%;
}

.spouse-form ::v-deep .el-radio-group {
  display: flex;
  gap: 20px;
}

/* 适配小屏幕 */
@media (max-width: 768px) {
  .search-bar {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }

  .search-input {
    width: 100%;
  }

  .gender-select {
    width: 100%;
  }

  .spouse-table ::v-deep .el-table__row {
    height: 40px;
  }

  .dialog-footer {
    text-align: center;
  }

  .dialog-footer .el-button {
    margin: 4px;
  }

  .spouse-dialog ::v-deep .el-dialog {
    width: 95% !important;
    margin: 2.5vh auto !important;
  }
}
</style>
